/*
 * Copyright (c) 2013 哈尔滨亿时代数码科技开发有限公司（www.hrbesd.com）. All rights reserved.
 * 
 * HRBESD PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.esd.ps;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.esd.db.model.AlipayInfo;
import com.esd.db.model.VtdNotice;
import com.esd.db.model.VtdParameter;
import com.esd.db.model.inspectorrecord;
import com.esd.db.model.manager;
import com.esd.db.model.markTimeMethod;
import com.esd.db.model.task;
import com.esd.db.model.taskWithBLOBs;
import com.esd.db.model.user;
import com.esd.db.model.worker;
import com.esd.db.model.workerRecord;
import com.esd.db.service.AlipayInfoService;
import com.esd.db.service.InspectorRecordService;
import com.esd.db.service.ManagerService;
import com.esd.db.service.MarkTimeMethodService;
import com.esd.db.service.PackService;
import com.esd.db.service.SalaryService;
import com.esd.db.service.TaskService;
import com.esd.db.service.UserService;
import com.esd.db.service.VtdNoticeService;
import com.esd.db.service.VtdParameterService;
import com.esd.db.service.WorkerRecordService;
import com.esd.db.service.WorkerService;
import com.esd.ps.model.WorkerRecordTrans;
import com.esd.ps.model.taskTrans;
import com.esd.ps.util.TaskMarkTime;
import com.esd.ps.util.TaskMarkTime1;

/**
 * 工作者
 * 
 * @author chen
 * 
 */
@Controller
@RequestMapping("/security")
public class WorkerController {
	private static final Logger logger = LoggerFactory.getLogger(WorkerController.class);
	@Autowired
	private TaskService taskService;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private WorkerService workerService;
	@Autowired
	private WorkerRecordService workerRecordService;
	@Autowired
	private PackService packService;
	@Autowired
	private SalaryService salaryService;
	@Autowired
	private MarkTimeMethodService markTimeMethodService;
	@Autowired
	private InspectorRecordService inspectorRecordService;
	@Autowired
	private VtdParameterService paramService;
	@Autowired
	private UserService userService;
	@Autowired
	private AlipayInfoService alipayInfoService;
	@Autowired
	private VtdNoticeService noticeService;
	/**
	 * 任务数不足
	 */
	@Value("${MSG_TASK_NOT_ENOUGH}")
	private String MSG_TASK_NOT_ENOUGH;
	/**
	 * 未审核
	 */
	@Value("${MSG_UNAUDIT}")
	private String MSG_UNAUDIT;
	/**
	 * 不合格
	 */
	@Value("${MSG_UNQUALIFY}")
	private String MSG_UNQUALIFY;
	/**
	 * 合格
	 */
	@Value("${MSG_QUALIFY}")
	private String MSG_QUALIFY;
	/**
	 * 放弃
	 */
	@Value("${MSG_GIVEUP}")
	private String MSG_GIVEUP;
	/**
	 * 审核中
	 */
	@Value("${MSG_AUDITING}")
	private String MSG_AUDITING;
	
	int workerMark = 0;

	/**
	 * 登录工作者页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/worker", method = RequestMethod.GET)
	public ModelAndView worker(HttpSession session) {
		int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
//		manager manager = managerService.selectByPrimaryKey(1);
		String workGroupCode = (String)session.getAttribute("workGroup");
//		String wgs = paramService.selectRemarksByParamVlaueAndParamType(workGroupCode, "workGroup");
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		String nowMonth = sdf.format(new Date());
		Double aduited = salaryService.getSumMarkTime2(workerId, nowMonth);
		if (aduited == null) {
			aduited = 0.00;
		}
//		DecimalFormat df = new DecimalFormat("#");
//		session.setAttribute("salary", df.format(aduited * manager.getSalary() / 3600));
//		session.setAttribute("salary", df.format(aduited * Double.parseDouble(wgs) / 3600));
		//获取计算工资节点  
		int salaryCountTiming = 0;
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	boolean flag = true;
	    for (int i = 0; i < outsourcerCodes.length; i++) {
			if (workGroupCode.equals(outsourcerCodes[i])) {
				flag = false;  //审核的是外包工作者
			}
		}
		List<VtdParameter> paramList = null;
		if(flag){
			paramList = paramService.selectParamByType(Constants.SALARY_COUNT_TIMING);//查询结算设置用的参数 只有一条数据   自营
		}else{
			paramList = paramService.selectParamByType(Constants.OUTSOURCER_SALARY_COUNT_TIMING);//查询外包结算设置用的参数 只有一条数据  外包
		}
		if(!paramList.isEmpty()){
			VtdParameter vp = paramList.get(0);
			salaryCountTiming = Integer.parseInt(vp.getParamValue());
		}
		//根据工资计算节点的不同 获取未审核时间 
		double aduiting = workerRecordService.getTaskMarkTimeForUninspection(workerId,salaryCountTiming);
		session.setAttribute("aduiting", aduiting);
//		session.setAttribute("aduiting", workerRecordService.getTaskMarkTimeMonthByWorkerIdAndMonth(workerId, "", "", "", 0, 1, 0));
		
		session.setAttribute("aduited", aduited);
		worker worker = workerService.selectByPrimaryKey(workerId);
		session.setAttribute("downing", worker.getDowning());
		int userLvl =Integer.parseInt(session.getAttribute(Constants.USER_LVL).toString());
		int typeCount = 1;
		if(userLvl>1){
			typeCount = 2;
		}
		session.setAttribute("typeCount", typeCount);	
		return new ModelAndView(Constants.WORKER + Constants.SLASH + Constants.WORKER);
	}

	// NullPointerException
	/**
	 * 检查并释放过时任务 返回此工作者的任务list
	 * 
	 * @param loginrName
	 * @return
	 */
	@RequestMapping(value = "/worker", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> workerPost(HttpSession session, HttpServletRequest request, int taskEffective,int packType) {

		Map<String, Object> map = new HashMap<String, Object>();

		int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));

		List<workerRecord> listAll = workerRecordService.getByWorkerIdAndEffective(workerId, 3, 0);
		
		String noticeFlag = session.getAttribute(Constants.NOTICE_FLAG).toString(); //通知公告标志
		if(noticeFlag.equals("1")){
			//查询出更新时间最靠前的一条公告显示
			VtdNotice notice = noticeService.getOneNoticeOrderByUpdateTimeDesc();
			map.put("notice", notice);
		}else{
			map.put("notice", "");
		}
		// 没有正在进行的任务
		if (listAll == null || listAll.isEmpty()) {
			int userLvl =Integer.parseInt(session.getAttribute(Constants.USER_LVL).toString());
			workerMark = 0;
			int downMaxCount = 0;
			int downOneCount = 0;
			// 可做任务的包数
			// int countPackDoing = taskService.getFreePackCount();
			// 当前下载的包的任务数
			int countTaskDoing = taskService.getCountTaskDoing(1);
			int auditingCount = workerRecordService.getCountByWorkerId(workerId, 1, 4);
			int countTaskDoing2 = 0 ;
			if(userLvl > 1){
				countTaskDoing2 = taskService.getCountTaskDoing(2);
			}	
			worker worker = workerService.selectByPrimaryKey(workerId);

			if(worker.getDownCount() != null){
				String downc = worker.getDownCount();
				String str[] = downc.split("/");
				downMaxCount = Integer.parseInt(str[0]);
				downOneCount = Integer.parseInt(str[1]);
			}else{
				manager manager = managerService.selectByPrimaryKey(1);
				downMaxCount = manager.getDownMaxCount();
				downOneCount = manager.getDownCount();
			}
			// worker可下载任务个数
			int downCount = 0;
			if ((downMaxCount - auditingCount) > downOneCount) {
				downCount = downOneCount;
			} else {
				downCount = (downMaxCount - auditingCount);
			}
			if (downCount > countTaskDoing) {
				downCount = countTaskDoing;
			}
			//
			int downCount2 = 0;
			if ((downMaxCount - auditingCount) > downOneCount) {
				downCount2 = downOneCount;
			} else {
				downCount2 = (downMaxCount - auditingCount);
			}
			if (downCount2 > countTaskDoing2) {
				downCount2 = countTaskDoing2;
			}
			//
			String noteId = packService.getNoteIdByPackId(0);
			// map.put(Constants.COUNTPACKDOING, countPackDoing);
			map.put(Constants.COUNTTASKDOING, countTaskDoing);
			map.put("downCount", downCount);
			
			map.put("countTaskDoing2", countTaskDoing2);
			map.put("downCount2", downCount2);
			
			map.put("noteId", noteId);
			map.put(Constants.WORKERMARK, 0);
			return map;
		}
		
		//   2016-08-05 修改了查询语句 原始循环中查询数据库效率不高  
//		List<workerRecord> listWorkerRecord = workerRecordService.getByWorkerIdAndEffective(workerId, taskEffective, 0);
//		logger.debug("listWorkerRecord:{},", listWorkerRecord);

//		workerMark = 1;
//		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
//		Date downloadTime = new Date();
//		int packLockTime = 0;
//		List<taskTrans> list = new ArrayList<taskTrans>();
//		for (Iterator<workerRecord> iterator = listWorkerRecord.iterator(); iterator.hasNext();) {
//			workerRecord workerRecord = (workerRecord) iterator.next();
//			downloadTime = workerRecord.getTaskDownTime();
//			packLockTime = workerRecord.getTaskLockTime();
//			taskTrans taskTrans = new taskTrans();
//			if (workerRecord.getTaskDownTime() == null) {
//				taskTrans.setTaskDownloadTime(Constants.EMPTY);
//			} else {
//				taskTrans.setTaskDownloadTime(sdf.format(workerRecord.getTaskDownTime()));
//			}
//			taskTrans.setTaskId(workerRecord.getTaskId());
//			taskTrans.setNoteId(packService.getNoteIdByPackId(workerRecord.getPackId()));
//			taskTrans.setTaskName(workerRecord.getTaskName().split("@")[0]);
//			taskTrans.setInspectorrecordId(workerRecord.getInspectorrecordId());
//			taskTrans.setUnqualifiedCount(workerRecord.getUnqualifiedCount());
//			
//			long overTime = packLockTime - (new Date().getTime() - downloadTime.getTime());
//			taskTrans.setOverTime(overTime);
//			logger.debug("TaskName:{}", workerRecord.getTaskName());
//			list.add(taskTrans);
//		}
		
		List<Map<String,Object>> showMaps = workerRecordService.getShowMapListForWorkerJsp(workerId, taskEffective, 0);
		logger.debug("showMaps:{},", showMaps);
		
		workerMark = 1;
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		Date downloadTime = new Date();
		long packLockTime = 0;
		List<taskTrans> list = new ArrayList<taskTrans>();
		
		for (Map<String, Object> m : showMaps) {
			downloadTime = (Date)m.get("taslDownTime");
			packLockTime = (long)m.get("taskLockTime");
			taskTrans taskTrans = new taskTrans();
			if (downloadTime == null) {
				taskTrans.setTaskDownloadTime(Constants.EMPTY);
			} else {
				taskTrans.setTaskDownloadTime(sdf.format(downloadTime));
			}
			taskTrans.setTaskId((int)m.get("taskId"));
			taskTrans.setNoteId((String)m.get("noteId"));
			String taskName = (String)m.get("taskName");
			taskTrans.setTaskName(taskName.substring(0, taskName.lastIndexOf("@")));
			taskTrans.setInspectorrecordId((int)m.get("inspectorRecordId"));
			taskTrans.setUnqualifiedCount((int)m.get("unqualifiedCount"));
			if(taskEffective==2){
				taskTrans.setInspNum((int)m.get("inspNum"));  //审核不合格退回任务数
			}
			long overTime = packLockTime - (new Date().getTime() - downloadTime.getTime());
			taskTrans.setOverTime(overTime);
			logger.debug("TaskName:{}", taskName);
			list.add(taskTrans);
		}
		Date begin;
		try {
			begin = sdf.parse(sdf.format(downloadTime));
			Date end = sdf.parse(sdf.format(new Date()));
			long between = (end.getTime() - begin.getTime());// 毫秒
			long mm = packLockTime - between;
			logger.debug("packLockTime:{},between:{},mm:{}", packLockTime, between, mm);
			map.clear();
			map.put(Constants.WORKERMARK, 1);
			map.put("list", list);
			map.put("mm", mm);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		session.setAttribute(Constants.WORKER_ID, workerId);
		return map;
	}

	/**
	 * 获得不合格任务的说明
	 * 
	 * @param inspectorrecordId
	 * @return
	 */
	@RequestMapping(value = "/getInspectrecord", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getInspectrecordPost(int inspectorrecordId) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (inspectorrecordId > 0) {
			inspectorrecord inspectorrecord = inspectorRecordService.selectByPrimaryKey(inspectorrecordId);
			map.put("note", inspectorrecord.getNote());
			if(inspectorrecord.getImgName()!=null&&(!inspectorrecord.getImgName().equals(""))){
				map.put("imgUrl", "/uploadImages/"+inspectorrecord.getImgName());
			}else{
				map.put("imgUrl", "");
			}
			map.put("inspNum", inspectorrecord.getInspNum());
		}
		return map;
	}

	/**
	 * 放弃任务
	 * 
	 * @param session
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "/GiveUpTask", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> GiveUpTaskPost(HttpSession session, int taskId) {
		Map<String, Object> map = new HashMap<String, Object>();
		int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
		StackTraceElement[] items = Thread.currentThread().getStackTrace();
		if(workerRecordService.updateByGiveUp(workerId, taskId, 0, items[1].toString())>0){
			task task = new task();
			task.setWorkerId(0);
			task.setVersion(1);
			task.setTaskMarkTime(0.00);
			task.setTaskUpload(false);
			task.setUpdateId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
			task.setTaskId(taskId);
			taskService.updateByTaskId(task);
		}else{
			map.put(Constants.REPLAY, 0);
			return map;
		}
	
//		int packId = workerRecordService.getPackIdByTaskId(taskId);
//		if (taskService.getUndoTaskCountByPackId(packId) > 0) {
//			packWithBLOBs pack = new packWithBLOBs();
//			pack.setPackId(packId);
//			pack.setPackStatus(0);
//			packService.updateByPrimaryKeySelective(pack);
//		}
		map.put(Constants.REPLAY, 1);
		return map;
	}
	/**
	 * 工资单
	 * @return
	 */
	@RequestMapping(value = "/workerSalary", method = RequestMethod.GET)
	public ModelAndView workerSalaryGET() {
		return new ModelAndView(Constants.WORKER + Constants.SLASH + "workerSalary");
	}
	/**
	 * 
	 * @param session
	 * @param page
	 * @param downPackName
	 * @return
	 */
	@RequestMapping(value = "/workerMonthSalary", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> workerMonthSalaryPOST(HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
		int workerId = workerService.getWorkerIdByUserId(userId);
//		manager m = managerService.selectByPrimaryKey(1);
//		String workGroupCode = (String)session.getAttribute("workGroup");
//		String wgs = paramService.selectRemarksByParamVlaueAndParamType(workGroupCode, "workGroup");
		List<Map<String,Object>> workerSalaryList = salaryService.getWorkerSalaryByWorkerId(workerId);
		map.put("list", workerSalaryList);
//		if(m.getSalary()>0){
//			map.put("salary",m.getSalary());
//		}else{
//			map.put("salary",0);
//		}	
//		map.put("salary",Double.parseDouble(wgs));
		return map;
	}
	/**
	 * worker的down pack完成历史页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/workerHistoryPack", method = RequestMethod.GET)
	public ModelAndView workerHistoryPackGET() {
		return new ModelAndView(Constants.WORKER + Constants.SLASH + Constants.WORKEHISTORYPACK);
	}

	/**
	 * worker的down pack完成历史页列表
	 * 
	 * @param session
	 * @param page
	 * @param downPackName
	 * @return
	 */
	@RequestMapping(value = "/workerHistoryPack", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> workerHistoryPackPOST(HttpSession session, int page, String downPackName) {
		Map<String, Object> map = new HashMap<String, Object>();

		int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));

		//SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		int totle = workerRecordService.getDownPackNameCountByworkerIdGroupByDownPackName(workerId, downPackName);
		//List<WorkerDownPackHistoryTrans> list = new ArrayList<>();
		int totlePage = 0;
		if (totle == 0) {
			map.clear();
			map.put(Constants.TOTLE, totle);
			map.put(Constants.TOTLE_PAGE, totlePage);
			map.put(Constants.LIST, null);
			return map;
		}
		List<Map<String,Object>> list = workerRecordService.getWorkerHis(workerId, page, Constants.ROW);
//		List<workerRecord> workerRecordList = workerRecordService.getWorkerRecordLikeDownPackName(workerId, page, downPackName, Constants.ROW);
//		logger.debug("workerRecordList:{}", workerRecordList);
//		for (Iterator<workerRecord> iterator = workerRecordList.iterator(); iterator.hasNext();) {
//			workerRecord workerRecord = (workerRecord) iterator.next();
//			WorkerDownPackHistoryTrans workerDownPackHistoryTrans = new WorkerDownPackHistoryTrans();
//			workerDownPackHistoryTrans.setTaskCount(workerRecordService.getTaskCountByDownPackName(workerRecord.getDownPackName()));
//			workerDownPackHistoryTrans.setDownPackName(workerRecord.getDownPackName());
//			logger.debug("status:{}", workerRecordService.getPackStatuByDownPackName(workerRecord.getDownPackName()));
//			if (workerRecordService.getPackStatuByDownPackName(workerRecord.getDownPackName()) > 0) {
//				workerDownPackHistoryTrans.setPackStatu(Constants.ZERO);
//			} else {
//				workerDownPackHistoryTrans.setPackStatu(Constants.ONE);
//			}
//
//			if (workerRecord.getTaskDownTime() == null) {
//				workerDownPackHistoryTrans.setDownTime(Constants.EMPTY);
//			} else {
//				workerDownPackHistoryTrans.setDownTime(sdf.format(workerRecord.getTaskDownTime()));
//			}
//			list.add(workerDownPackHistoryTrans);
//		}
		map.clear();
		totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, totlePage);
		map.put(Constants.LIST, list);
		return map;
	}

	/**
	 * worker的任务历史详细列表
	 * 
	 * @param downPackName
	 * @return
	 */
	@RequestMapping(value = "/workerHistoryTask", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> workerHistoryTaskPOST(String downPackName) {
		Map<String, Object> map = new HashMap<String, Object>();
		logger.debug("downPackName:{}", downPackName);

		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		List<WorkerRecordTrans> list = new ArrayList<WorkerRecordTrans>();
		List<workerRecord> workerRecordList = workerRecordService.getAllByDownPackName(downPackName);
		if (workerRecordList == null) {
			return null;
		}
		for (Iterator<workerRecord> iterator = workerRecordList.iterator(); iterator.hasNext();) {
			workerRecord workerRecord = (workerRecord) iterator.next();
			WorkerRecordTrans workerRecordTrans = new WorkerRecordTrans();
			workerRecordTrans.setDownPackName(downPackName);
			workerRecordTrans.setTaskDownTime(sdf.format(workerRecord.getTaskDownTime()));
			if (workerRecord.getTaskEffective() == 0) {
				workerRecordTrans.setTaskEffective(MSG_UNAUDIT);
			} else if (workerRecord.getTaskEffective() == 2) {
				workerRecordTrans.setTaskEffective(MSG_UNQUALIFY);
			} else if (workerRecord.getTaskEffective() == 1) {
				workerRecordTrans.setTaskEffective(MSG_QUALIFY);
			} else if (workerRecord.getTaskEffective() == 3 || workerRecord.getTaskEffective() == 4) {
				workerRecordTrans.setTaskEffective(MSG_AUDITING);
			}
			workerRecordTrans.setEffective(workerRecord.getTaskEffective());
			workerRecordTrans.setTaskLockTime(workerRecord.getTaskLockTime() / 3600000);
			if (workerRecord.getTaskMarkTime() == null) {
				workerRecordTrans.setTaskMarkTime(0.00);
			} else {
				workerRecordTrans.setTaskMarkTime(workerRecord.getTaskMarkTime());
			}
			workerRecordTrans.setTaskId(workerRecord.getTaskId());
			workerRecordTrans.setTaskName(workerRecord.getTaskName().substring(0, workerRecord.getTaskName().lastIndexOf("@")));
			workerRecordTrans.setTaskStatus(workerRecord.getTaskStatu());
			if (workerRecord.getTaskUploadTime() == null) {
				workerRecordTrans.setTaskUploadTime(Constants.EMPTY);
			} else {
				workerRecordTrans.setTaskUploadTime(sdf.format(workerRecord.getTaskUploadTime()));
			}
			list.add(workerRecordTrans);
		}
		map.put(Constants.LIST, list);
		return map;
	}

	/**
	 * 再次下载任务包
	 * 
	 * @param downPackName
	 * @return
	 */
	@RequestMapping(value = "/downOncePack", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> downOncePack(String downPackName, HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		String url = WorkerController.url(request);
		File f = new File(url);
		File zipFile = null;
		// 项目在服务器上的远程绝对地址
		// String serverAndProjectPath = request.getLocalAddr() +
		// Constants.COLON + request.getLocalPort() + request.getContextPath();
		// 文件所谓的远程绝对路径
		// String wrongPath = Constants.HTTP + serverAndProjectPath +
		// Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH +
		// downPackName;
		String wrongPath = Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + downPackName;
		if (f.exists()) {
			zipFile = new File(url + Constants.SLASH + downPackName);
			if (zipFile.exists()) {
				//System.out.println(url + Constants.SLASH + downPackName);
				map.put(Constants.WRONGPATH, wrongPath);
				return map;
			}
		} else {
			f.mkdir();
		}
		try {
			zipFile.createNewFile();
			int workerId = Integer.parseInt(session.getAttribute(Constants.WORKER_ID).toString());
			List<taskWithBLOBs> list = taskService.getDoingTaskByWorkerId(workerId);
			logger.debug("workerId:{},list1:{}", workerId, list);
			this.wrongPath(zipFile, list);
			workerRecord workerRecord = new workerRecord();
			workerRecord.setUpdateTime(new Date());
			workerRecord.setDownUrl(wrongPath);
			workerRecord.setDownPackName(downPackName);
			int a = workerRecordService.updateBydownPackName(workerRecord);
			logger.debug("a:{}", a);
		} catch (IOException e) {
			e.printStackTrace();
		}

		map.put(Constants.WRONGPATH, wrongPath);
		logger.debug("wrongPath:{}", wrongPath);
		return map;
	}

	/**
	 * 下载某一个任务
	 * 
	 * @param response
	 * @param taskName
	 */
	@RequestMapping(value = "/downOneTask", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> downOneTask(HttpServletRequest request, String taskName, int taskId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String url = WorkerController.url(request);
		File f = new File(url);
		String zipName = taskName.substring(0, taskName.lastIndexOf(Constants.POINT)) + Constants.POINT + Constants.ZIP;
		File zipFile = new File(url + Constants.SLASH + zipName);
		// 项目在服务器上的远程绝对地址
		// String serverAndProjectPath = request.getLocalAddr() +
		// Constants.COLON + request.getLocalPort() + request.getContextPath();
		// 文件所谓的远程绝对路径
		// String wrongPath = Constants.HTTP + serverAndProjectPath +
		// Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + zipName;
		String wrongPath = Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + zipName;
		if (!f.exists()) {
			f.mkdir();
		}
		try {

			zipFile.createNewFile();
			taskWithBLOBs task = taskService.selectByPrimaryKey(taskId);
			task.setTaskName(task.getTaskName().substring(0, task.getTaskName().lastIndexOf("@")));
			List<taskWithBLOBs> list = new ArrayList<taskWithBLOBs>();
			list.add(task);
			this.wrongPath(zipFile, list);
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put(Constants.WRONGPATH, wrongPath);
		return map;
	}

	/**
	 * 下载任务(wav格式)
	 * @param response
	 * @param downTaskCount
	 * @param session
	 * @param request
	 * @param packType
	 * @return
	 */
	@RequestMapping(value = "/downTask", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> downTask(final HttpServletResponse response, int downTaskCount, HttpSession session, HttpServletRequest request,int packType) {
		Map<String, Object> map = new HashMap<String, Object>();
		//在session里取得user_id
		int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
		//int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
		//在worker表通过user_id获得worker对象
		worker w = workerService.getWorkerByUserId(userId);
		if(w == null){
			map.put("replay",1);
			return map;
		}
		String downloadLock = "";
		List<VtdParameter>workGroups = paramService.selectParamByType(Constants.WORK_GROUP);
		for (VtdParameter wg : workGroups) {
			if(wg.getParamValue().equals(w.getWorkGroupCode())){
				downloadLock = wg.getBackup1();
			}
		}
		
		String zzhUserStatus = session.getAttribute("zzhUserStatus").toString();
		if(zzhUserStatus.equals("false")){
			map.put("replay",3);
			map.put("msg", "当前账号不可用,咨询官方群内客服工作人员，咨询QQ号:3158586651.");
			return map;
		}
		if(downloadLock.equals(Constants.LOCK)){
			map.put("replay",3);
			map.put("msg", "当前工作组有未修改完成任务,暂时不能下载新任务,请尽快修改问题任务!");
			return map;
		}
		
		//获得worker_id
		int workerId = w.getWorkerId();
		//通过worker表的downing字段判断此worker的下载状态
		//downing = 1 表示 现在中
		if(w.getDowning() == 1){
			map.put("replay",1);
			return map;
		}else{
			//worker_record表通过worker_id查询此worker正在做的任务数量
			int doingtaskcount = workerRecordService.getDoingTaskCountByWorkerId(workerId);
			if(doingtaskcount>0){
				map.put("replay",1);
				return map;
			}
		}
		//更改session中downing参数的为1
		session.setAttribute("downing", 1);
		logger.debug("downTaskCount:{}", downTaskCount);
		//通过表task中pack_type字段查询现在可做任务数
		int countTaskDoing = taskService.getCountTaskDoing(packType);
		// 查看先可做任务数是否小于需求
		if (countTaskDoing < downTaskCount) {
			// String nowCountTaskDoing=countTaskDoing + "";
			map.put(Constants.MESSAGE, MSG_TASK_NOT_ENOUGH);
			session.setAttribute("downing", 0);
			return map;
		}
		
		//String realName = workerService.getWorkerRealNameByWorkerId(workerId);
		//获取worker的真实名字
		String realName = w.getWorkerRealName();
		// int packId = packService.getPackIdOrderByPackLvl();
		// 更新工作者下载状态
		worker worker = new worker();
		worker.setWorkerId(workerId);
		worker.setDowning(1);
		//更新worker表的downing
		workerService.updateByPrimaryKeySelective(worker);
		//获得根目录地址
		String url = WorkerController.url(request);
		logger.debug("url:{}", url);
		//获得时间点
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
		//生成下载任务的压缩包名
		String downPackName = sdf.format(new Date()) + Constants.UNDERLINE + downTaskCount + Constants.UNDERLINE + userId + Constants.POINT + Constants.ZIP;
		String wrongPath = Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + downPackName;
		//查询他时刻表可下载任务的list  String downPackName,String wrongPath,String realName,String userName
//TODO 测试用		List<taskWithBLOBs> list = taskService.updateWorkerIdDowningTask(downTaskCount, 0, userId, workerId,packType,downPackName,wrongPath,realName,session.getAttribute(Constants.USER_NAME).toString());
		List<taskWithBLOBs> list = taskService.getTaskOrderByTaskLvl(downTaskCount, 0, userId, workerId,packType,downPackName,wrongPath,realName,session.getAttribute(Constants.USER_NAME).toString());
		if (list == null) {
			session.setAttribute("downing", 0);
			return null;
		}
		File f = new File(url);
		if (f.exists() == false) {
			f.mkdir();
		}
		//生成压缩包文件
		File zipFile = new File(url + Constants.SLASH + downPackName);
		if (zipFile.exists()) {
			zipFile.delete();
		}
		// 项目在服务器上的远程绝对地址
		// String serverAndProjectPath = request.getLocalAddr() +
		// Constants.COLON + request.getLocalPort() + request.getContextPath();
		// 文件所谓的远程绝对路径
		// String wrongPath = Constants.HTTP + serverAndProjectPath +
		// Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH +
		// downPackName;
		
		//任务包地址（任务包的下载地址）
		logger.debug("wrongPath:{}", wrongPath);
		try {
			zipFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
			byte[] bufs = new byte[1024 * 10];
			for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
				taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
				//获得任务名
				String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName().substring(0, taskWithBLOBs.getTaskName().lastIndexOf("@"));
				// 创建ZIP实体,并任务添加进压缩包
				ZipEntry zipEntry = new ZipEntry(fileName);
				zos.putNextEntry(zipEntry);
				//从task表获取任务流
				byte[] data = taskWithBLOBs.getTaskWav();
				//转成字节流
				InputStream is = new ByteArrayInputStream(data);
				// 读取待压缩的文件并写进压缩包里
				BufferedInputStream bis = new BufferedInputStream(is, 1024);
				int read;
				while ((read = bis.read(bufs)) > 0) {// , 0, 2048
					zos.write(bufs, 0, read);//
				}
				// zos.closeEntry();
				bis.close();
				is.close();
				// 更新task表

				// 更新worker_record 工作者的任务记录
//				workerRecord workerRecord = new workerRecord();
//				workerRecord.setCreateTime(new Date());
//				workerRecord.setTaskOverTime(new Date());
//				workerRecord.setDownPackName(downPackName);
//				workerRecord.setDownUrl(wrongPath);
//				workerRecord.setPackId(taskWithBLOBs.getPackId());
//				workerRecord.setPackName(packService.getPackNameByPackId(taskWithBLOBs.getPackId()));
//				workerRecord.setTaskDownTime(new Date());
//				workerRecord.setTaskId(taskWithBLOBs.getTaskId());
//				int packLockTime = packService.getPackLockTime(taskWithBLOBs.getPackId());
//				if (packLockTime > 0) {
//					workerRecord.setTaskLockTime(packLockTime);
//				}
//				workerRecord.setTaskName(taskWithBLOBs.getTaskName());
//				//真名
//				workerRecord.setRealName(realName);
//				workerRecord.setTaskStatu(0);
//				workerRecord.setWorkerId(workerId);
//				workerRecord.setUserName(session.getAttribute(Constants.USER_NAME).toString());
//				StackTraceElement[] items1 = Thread.currentThread().getStackTrace();
//				workerRecord.setCreateMethod(items1[1].toString());
//				workerRecordService.insertSelective(workerRecord);
			}
			session.setAttribute(Constants.WORKERMARK, 1);
			zos.close();// 必须关闭,否则最后一个文件写入为0kb
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
		/**
		 * 查看包任务情况,如果任务都已下载则更行packStatus
		 */
		// if (taskService.getUndoTaskCountByPackId(packId) == 0) {
		// packWithBLOBs pack = new packWithBLOBs();
		// pack.setPackId(packId);
		// pack.setPackStatus(2);
		// packService.updateByPrimaryKeySelective(pack);
		// }
		logger.debug("wrongPath:{}", wrongPath);
		map.put(Constants.WRONGPATH, wrongPath);
		map.put("replay", 0);
		session.setAttribute("downing", 0);
		// 更新工作者下载状态
		worker.setDowning(0);
		workerService.updateByPrimaryKeySelective(worker);
		return map;
	}

	/**
	 * worker上传TAG和TextGrid
	 * 
	 * @param files
	 * @param session
	 * @param taskWithBLOBs
	 */
	@RequestMapping(value = "/upTagAndTextGrid", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> upTagAndTextGrid(@RequestParam("file") CommonsMultipartFile[] files, HttpSession session, taskWithBLOBs taskWithBLOBs, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
		boolean flag = false;
		logger.debug("workerId:{}", workerId);
		List<task> listTask = taskService.getAllDoingTaskByWorkerId(workerId);
		if (files.length == 0) {
			return null;
		}
		List<String> listMath = new ArrayList<String>();
		List<String> listAll = new ArrayList<String>();
		// int task_id = Constants.ZERO;
		for (int i = 0; i < files.length; i++) {
			listAll.add(files[i].getOriginalFilename());
			logger.debug(files[i].getOriginalFilename());
		}
		//上传批次表示
		String uploadUUID = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
		for (Iterator<task> iterator = listTask.iterator(); iterator.hasNext();) {
			task task = (task) iterator.next();
			String taskName = task.getTaskName().substring(0, task.getTaskName().lastIndexOf("@"));
			for (int i = 0; i < files.length; i++) {
//				try {
//					files[i].getInputStream();
//				} catch (IOException e2) {
//					e2.printStackTrace();
//				}
				String nameWav = files[i].getOriginalFilename().substring(0, files[i].getOriginalFilename().lastIndexOf(Constants.POINT)) + Constants.POINT + Constants.WAV;
				// nameWav上传的文件名在,taskName工作者正在做的任务名
				if (taskName.equalsIgnoreCase(nameWav)) {
					int taskId = task.getTaskId();
					String markTimeName = packService.getTaskMarkTimeName(task.getPackId());
					int uploadFileCount = Integer.parseInt(markTimeName.split("_")[1]);
					// 上传连个文件textgrid和tag
					if (uploadFileCount == 2) {
						for (int j = 0; j < files.length; j++) {
							if (files[i].getOriginalFilename().substring(0, files[i].getOriginalFilename().lastIndexOf(Constants.POINT)).equalsIgnoreCase(files[j].getOriginalFilename().substring(0, files[j].getOriginalFilename().lastIndexOf(Constants.POINT)) )
									&& !files[i].getOriginalFilename().equalsIgnoreCase(files[j].getOriginalFilename())) {
								if (files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf(Constants.POINT)+1).equalsIgnoreCase(Constants.TEXTGRID)
										|| files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf(Constants.POINT)+1).equalsIgnoreCase(Constants.TAG)) {
									flag = true;
									break;
								}
							}
						}
					} else if (uploadFileCount == 1) {
						String originalFilename = files[i].getOriginalFilename();
						if (originalFilename.substring(originalFilename.lastIndexOf(Constants.POINT)+1,originalFilename.length()).equalsIgnoreCase(Constants.TEXTGRID)) {
							flag = true;
						}
					}
					if (flag) {
						String uploadTaskNameI = files[i].getOriginalFilename();

						byte[] bytes = files[i].getBytes();
						// String nameLast =
						// files[i].getOriginalFilename().substring((files[i].getOriginalFilename().indexOf(Constants.POINT)
						// + 1), files[i].getOriginalFilename().length());
						String nameLast = files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf(Constants.POINT)+1);
						if (nameLast.equalsIgnoreCase(Constants.TEXTGRID)) {
							int packId = task.getPackId();
							markTimeMethod markTimeMethod = markTimeMethodService.getByPrimaryKey(packService.getTaskMarkTimeId(packId));
							String keyWords = "\"" + markTimeMethod.getKeywords() + "\"";
							double taskMarkTime = 0;
							InputStream is = null;
							try {
								is = files[i].getInputStream();
								TaskMarkTime tmt = new TaskMarkTime1();
								taskMarkTime = tmt.textGrid1(is, keyWords);
								if (taskMarkTime == 10000) {
									map.clear();
									map.put(Constants.REPLAY, 0);
									map.put(Constants.MESSAGE, "文件与包的时间统计方法不匹配,请联系管理员!");
									return map;
								}
								is.close();
							} catch (IOException e) {
								e.printStackTrace();
							}finally{
								if(is != null){
									try {
										is.close();
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
							}
							Map<String, Object> recordIdAndUnqualifiedCount = workerRecordService.getPkIdAndUnqualifiedCountByTaskId(taskId);
							int recordId = Integer.parseInt(recordIdAndUnqualifiedCount.get("recordId").toString());
							int unqualifiedCount = Integer.parseInt(recordIdAndUnqualifiedCount.get("unqualifiedCount").toString());
							String createMd5 = DigestUtils.md5Hex(bytes);
							// 更新workerRecord表
							workerRecord workerRecord = new workerRecord();
							workerRecord.setTaskUploadTime(new Date());
							workerRecord.setTaskOverTime(new Date());
							workerRecord.setTaskStatu(1);
							workerRecord.setTaskEffective(0);
							workerRecord.setTaskMarkTime(Double.parseDouble(String.format(Constants.SPILT_TWELVE, taskMarkTime)));
//							workerRecord.setRecordId(workerRecordService.getPkIDByTaskId(taskId));
							workerRecord.setRecordId(recordId);
							StackTraceElement[] items1 = Thread.currentThread().getStackTrace();
							workerRecord.setUpdateMethod(items1[1].toString());
							workerRecord.setUploadUUID(uploadUUID);
							if(unqualifiedCount == 0){
								workerRecord.setCreateMd5(createMd5);
							}
							workerRecordService.updateByPrimaryKeySelective(workerRecord);
							// 更新task表
							taskWithBLOBs.setTaskMarkTime(Double.parseDouble(String.format(Constants.SPILT_TWELVE, taskMarkTime)));
							taskWithBLOBs.setTaskTextgrid(bytes);
							taskWithBLOBs.setTaskId(taskId);
							taskWithBLOBs.setTaskUpload(true);
							taskWithBLOBs.setTaskUploadTime(new Date());
							StackTraceElement[] items = Thread.currentThread().getStackTrace();
							taskWithBLOBs.setUpdateMethod(items[1].toString());
							taskWithBLOBs.setTaskEffective(null);
							taskService.updateByPrimaryKeySelective(taskWithBLOBs);

							listMath.add(uploadTaskNameI);
							// task_id = taskId;
						} else if (nameLast.equalsIgnoreCase(Constants.TAG)) {
							taskWithBLOBs.setTaskTag(bytes);
							taskWithBLOBs.setTaskId(taskId);
							taskWithBLOBs.setTaskUploadTime(new Date());
							StackTraceElement[] items = Thread.currentThread().getStackTrace();
							taskWithBLOBs.setUpdateMethod(items[1].toString());
							taskService.updateByPrimaryKeySelective(taskWithBLOBs);
							listMath.add(uploadTaskNameI);
						}
					}
				}
			}
		}

		int doingTaskCount = workerRecordService.getDoingTaskCountByWorkerId(workerId);
		if (doingTaskCount == 0) {
			workerRecord workerRecord = workerRecordService.getWorkerRecordByWorkerId(workerId);
			String url = WorkerController.url(request);
			File file = new File(url + Constants.SLASH + workerRecord.getDownPackName());
			if (file.exists()) {
				file.delete();
			}
		}
		map.put(Constants.REPLAY, 1);
		map.put(Constants.LISTMATH, listMath);
		map.put(Constants.LISTALL, listAll);
		return map;
	}
	/**
	 * 取得项目根目录
	 * 
	 * @param request
	 * @return
	 */
	public static String url(HttpServletRequest request) {
		String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
		url = url + Constants.WORKERTEMP;
		File f = new File(url);
		if (f.exists()) {
			return url;
		}
		f.mkdir();
		return url;
	}

	/**
	 * 打包方法
	 * 
	 * @param zipFile
	 * @param list
	 * @return
	 */
	public String wrongPath(File zipFile, List<taskWithBLOBs> list) {
		logger.debug("list2:{}", list);
		try {
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
			byte[] bufs = new byte[1024 * 10];
			for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
				taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
				String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName().substring(0, taskWithBLOBs.getTaskName().lastIndexOf("@"));
				// 创建ZIP实体,并添加进压缩包
				ZipEntry zipEntry = new ZipEntry(fileName);
				zos.putNextEntry(zipEntry);
				byte[] data = taskWithBLOBs.getTaskWav();
				InputStream is = new ByteArrayInputStream(data);
				// 读取待压缩的文件并写进压缩包里
				BufferedInputStream bis = new BufferedInputStream(is, 1024);
				int read;
				while ((read = bis.read(bufs)) > 0) {
					zos.write(bufs, 0, read);//
				}
				// zos.closeEntry();
				bis.close();
				is.close();
				// 更新task表
			}
			for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
				taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
				String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName().substring(0, taskWithBLOBs.getTaskName().lastIndexOf("@"));
				String textgridName = fileName.replace(".wav", ".textgrid");
				// 创建ZIP实体,并添加进压缩包
				ZipEntry zipEntry = new ZipEntry(textgridName);
				zos.putNextEntry(zipEntry);
				byte[] data = taskWithBLOBs.getTaskTextgrid();
				InputStream is = new ByteArrayInputStream(data);
				// 读取待压缩的文件并写进压缩包里
				BufferedInputStream bis = new BufferedInputStream(is, 1024);
				int read;
				while ((read = bis.read(bufs)) > 0) {
					zos.write(bufs, 0, read);//
				}
				// zos.closeEntry();
				bis.close();
				is.close();
				// 更新task表
			}
			zos.close();// 必须关闭,否则最后一个文件写入为0kb
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
		return "";
	}
//	public void test (){
//		System.out.println(salaryService.getWorkerSalaryByWorkerId(25));
//	}
	
	/**
	 * 重置下载按钮
	 * @param loginrName
	 * @return
	 */
	@RequestMapping(value = "/resetDownload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> resetDownloadPost(HttpSession session, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		//根据userId获得workerId
		int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()));
		
		//重置下载按钮    
		int resetFlag = workerService.checkDownloadByWorkerId(workerId);
		if(resetFlag==0){
			workerService.resetDownloadByWorkerId(workerId);
			map.put("msg", 1);   //已重置
		}else if(resetFlag==2){
			map.put("msg", 2);   //未超时
		}else{
			map.put("msg", 0);   //没有处于正在下载状态
		}
		return map;
	}
	
	/**
	 * 转到查看被推荐人列表页面
	 * 
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getViewOfReferralsForWorkerPage", method = RequestMethod.GET)
	public ModelAndView getViewOfReferralsForWorkerPageGET(HttpServletRequest request) {
		int userId = (int)request.getSession().getAttribute("userId");
		Map<String, Object> model = new HashMap<>();
		user u = userService.getByPrimaryKey(userId);
		model.clear();
		model.put(Constants.USER_ID, userId);
		model.put(Constants.CHOOSEUSERNAME, u.getUsername());
		model.put("thisUserReferrerId", u.getReferrerId());
		return new ModelAndView("worker/viewOfReferralsForWorkerPage", Constants.MODEL, model);
	}

	/**
	 * 查看被推荐人列表
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/getViewOfReferralsForWorkerPage", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getViewOfReferralsForWorkerPagePost(int userId, int page, String referralUsernameCondition,
			String dateCondition) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
		//查询被推荐人相关信息
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("referrer", userId); //推荐人ID
		condition.put("referralUsername", referralUsernameCondition);//页面查询条件
		int totle = userService.getReferralUsersCount(condition);
		condition.put("begin", ((page - 1) * Constants.ROW)); //分页
		condition.put("end", Constants.ROW);    //分页
		List<user> users = userService.getReferralUsers(condition);
		int totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
		map.put(Constants.LIST, users);
		map.put(Constants.TOTLE, totle);// totleG
		map.put(Constants.TOTLE_PAGE, totlePage);
		//标注时间
		for (user u : users) {
			worker worker = workerService.getWorkerByUserId(u.getUserId());
			Map<String, Object> tempMap = salaryService.getSumMarkTimeAndSalaryValueForViewOfReferrals(worker.getWorkerId(), dateCondition);
			Map<String,Object> view = new HashMap<String,Object>();
			view.put("username", u.getUsername());
			view.put("realName", worker.getWorkerRealName());
			view.put("marktime", Double.parseDouble(tempMap.get("markTime").toString())/3600);
			view.put("salaryValue", Math.round(Double.parseDouble(tempMap.get("salaryValue").toString())));
			resultList.add(view);
		}
		map.put(Constants.LIST, resultList);
		return map;
	}
	
	/**
	 * 跳转到支付信息查询页面
	 */
	@RequestMapping(value = "/alipayInfosSearchByworker", method = RequestMethod.GET)
	public ModelAndView alipayInfosSearchByworkerGet() {
		Map<String, Object> model = new HashMap<>();
		return new ModelAndView("worker/alipayInfosSearchByWorker", Constants.MODEL, model);
	}
	
	/**
	 * 查询支付宝支付列表
	 */
	@RequestMapping(value = "/queryAlipayListByWorker", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryAlipayListPost(HttpSession session, int page, String alipayBeginDate, String alipayEndDate, int alipayDateType, int alipayStatus) {
//		System.out.println(alipayAccount+"  "+payeeRealName+"  "+page+"  "+alipayBeginDate+"  "+alipayEndDate+"  "+alipayDateType+"  "+alipayStatus);
		int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
		worker worker = workerService.getWorkerByUserId(userId);
		int workerId = 0;
		if(worker!=null){
			workerId = worker.getWorkerId();
		}
		Map<String, Object> map = new HashMap<>();
		//查询支付信息数据
		List<AlipayInfo> alipayInfoList = alipayInfoService.queryAlipayInfoList(null,null,alipayBeginDate,alipayEndDate,alipayDateType,alipayStatus,page,Constants.ROW,workerId);
		List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
		double pageSalary = 0.0;
		for (AlipayInfo a : alipayInfoList) {
			if(a.getIsSuccess()){
				pageSalary = pageSalary+a.getAmount(); //计算当前页成功支付金额
			}
			Map<String,Object> result = new HashMap<String,Object>(); //装填页面显示用数据
			result.put("alipayId",a.getAlipayId()); 			
			result.put("alipayReturnCode",a.getAlipayReturnCode());   	
			result.put("alipayReturnMsg",a.getAlipayReturnMsg());		
			result.put("orderId",a.getOrderId());				
			result.put("outBizNo",a.getOutBizNo());				
			result.put("payDate",a.getPayDate());				
			result.put("subCode",a.getSubCode());				
			result.put("subMsg",a.getSubMsg());				
			result.put("payerRealName",a.getPayerRealName());		
			result.put("payeeRealName",a.getPayeeRealName());		
			result.put("payeeAccount",a.getPayeeAccount());		
			result.put("amount",a.getAmount());				
			result.put("isSuccess",a.getIsSuccess());          
			result.put("workerId",a.getWorkerId());  	
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateString = df.format(a.getCreateDate());
			result.put("createDate",dateString);  
			resultList.add(result);
		}
		//查询总数
		int totle = alipayInfoService.queryAlipayInfoTotle(null,null,alipayBeginDate,alipayEndDate,alipayDateType,alipayStatus,page,Constants.ROW,workerId);
		double totleSalary = alipayInfoService.queryTotleSalary(null,null,alipayBeginDate,alipayEndDate,alipayDateType,page,Constants.ROW,workerId);
		int totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW);
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, totlePage);
		map.put("list", resultList);
		map.put("pageSalary", Math.round((pageSalary*100.0))/100.0);
		map.put("totleSalary", Math.round((totleSalary*100.0))/100.0);
		return map;
	}
}
